﻿namespace Hidistro.UI.ControlPanel.utility
{
    using Hidistro.ControlPanel.Store;
    using Hidistro.Core;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Membership.Core.Enums;
    using Hidistro.UI.Common.Controls;
    using Hishop.Components.Validation;
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.IO;
    using System.IO.Compression;
    using System.Net;
    using System.Text;
    using System.Web.UI;

    public class AdminPage : Page
    {
        protected void CheckAuth()
        {
            string domainName = Globals.DomainName;
            string str2 = "openwapstore";
            string str3 = base.Request.FilePath.ToLower();
            if (str3.IndexOf("/wap/") > 0)
            {
                str2 = "openwapstore";
            }
            else if (str3.IndexOf("/vshop/") > 0)
            {
                str2 = "openvstore";
            }
            else if (str3.IndexOf("/alioh/") > 0)
            {
                str2 = "openaliohstore";
            }
            else if (str3.IndexOf("/app/") > 0)
            {
                str2 = "openmobile";
            }
            else
            {
                return;
            }
            try
            {
                if (Convert.ToInt32(this.PostData("http://ysc.kuaidiantong.cn/valid.ashx", "action=" + str2 + "&product=2&host=" + domainName).Replace("{\"state\":\"", "").Replace("\"}", "")) != 1)
                {
                    this.Page.Response.Redirect(Globals.GetAdminAbsolutePath("/AccessDenied.aspx?errormsg=抱歉，您暂未开通此服务！"), true);
                }
            }
            catch
            {
                this.Page.Response.Redirect(Globals.GetAdminAbsolutePath("/AccessDenied.aspx?errormsg=抱歉，您暂未开通此服务！"), true);
            }
        }

        private void CheckPageAccess()
        {
            IUser user = HiContext.Current.User;
            if (user.UserRole != UserRole.SiteManager)
            {
                this.Page.Response.Redirect(Globals.GetSiteUrls().Login, true);
            }
            else
            {
                SiteManager manager = user as SiteManager;
                if (!manager.IsAdministrator)
                {
                    AdministerCheckAttribute customAttribute = (AdministerCheckAttribute) Attribute.GetCustomAttribute(base.GetType(), typeof(AdministerCheckAttribute));
                    if ((customAttribute != null) && customAttribute.AdministratorOnly)
                    {
                        this.Page.Response.Redirect(Globals.GetAdminAbsolutePath("/AccessDenied.aspx"));
                    }
                    PrivilegeCheckAttribute attribute2 = (PrivilegeCheckAttribute) Attribute.GetCustomAttribute(base.GetType(), typeof(PrivilegeCheckAttribute));
                    if ((attribute2 != null) && !manager.HasPrivilege((int) attribute2.Privilege))
                    {
                        this.Page.Response.Redirect(Globals.GetAdminAbsolutePath("/accessDenied.aspx?privilege=" + attribute2.Privilege.ToString()));
                    }
                }
            }
        }

        protected virtual void CloseWindow()
        {
            string str = "var win = art.dialog.open.origin; win.location.reload();";
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered("ServerMessageScript"))
            {
                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "ServerMessageScript", "<script language='JavaScript' defer='defer'>" + str + "</script>");
            }
        }

        protected string CutWords(object obj, int length)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            string str = obj.ToString();
            if (str.Length > length)
            {
                return (str.Substring(0, length) + "......");
            }
            return str;
        }

        private string GenericReloadUrl(NameValueCollection queryStrings)
        {
            if ((queryStrings == null) || (queryStrings.Count == 0))
            {
                return base.Request.Url.AbsolutePath;
            }
            StringBuilder builder = new StringBuilder();
            builder.Append(base.Request.Url.AbsolutePath).Append("?");
            foreach (string str2 in queryStrings.Keys)
            {
                string str = queryStrings[str2].Trim().Replace("'", "");
                if (!(string.IsNullOrEmpty(str) || (str.Length <= 0)))
                {
                    builder.Append(str2).Append("=").Append(base.Server.UrlEncode(str)).Append("&");
                }
            }
            queryStrings.Clear();
            builder.Remove(builder.Length - 1, 1);
            return builder.ToString();
        }

        protected int GetFormIntParam(string name)
        {
            string str = base.Request.Form.Get(name);
            if (string.IsNullOrEmpty(str))
            {
                return 0;
            }
            try
            {
                return Convert.ToInt32(str);
            }
            catch (FormatException)
            {
                return 0;
            }
        }

        protected bool GetUrlBoolParam(string name)
        {
            string str = base.Request.QueryString.Get(name);
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
            try
            {
                return Convert.ToBoolean(str);
            }
            catch (FormatException)
            {
                return false;
            }
        }

        protected int GetUrlIntParam(string name)
        {
            string str = base.Request.QueryString.Get(name);
            if (string.IsNullOrEmpty(str))
            {
                return 0;
            }
            try
            {
                return Convert.ToInt32(str);
            }
            catch (FormatException)
            {
                return 0;
            }
        }

        protected void GotoResourceNotFound()
        {
            base.Response.Redirect(Globals.GetAdminAbsolutePath("ResourceNotFound.aspx"));
        }

        protected string ModiflyUrl(object count)
        {
            if (Convert.ToInt32(count) > 1)
            {
                return "EditMultiArticle.aspx";
            }
            return "EditSingleArticle.aspx";
        }

        protected override void OnInit(EventArgs e)
        {
            this.RegisterFrameScript();
         
            this.CheckPageAccess();
            base.OnInit(e);
        }

        public string PostData(string url, string postData)
        {
            string str = string.Empty;
            try
            {
                Uri requestUri = new Uri(url);
                HttpWebRequest request = (HttpWebRequest) WebRequest.Create(requestUri);
                byte[] bytes = Encoding.UTF8.GetBytes(postData);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = bytes.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
                using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
                {
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        Encoding encoding = Encoding.UTF8;
                        Stream stream3 = stream2;
                        if (response.ContentEncoding.ToLower() == "gzip")
                        {
                            stream3 = new GZipStream(stream2, CompressionMode.Decompress);
                        }
                        else if (response.ContentEncoding.ToLower() == "deflate")
                        {
                            stream3 = new DeflateStream(stream2, CompressionMode.Decompress);
                        }
                        using (StreamReader reader = new StreamReader(stream3, encoding))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                str = string.Format("获取信息错误：{0}", exception.Message);
            }
            return str;
        }

        protected virtual void RegisterFrameScript()
        {
            string key = "admin-frame";
            string script = string.Format("<script>if(window.parent.frames.length == 0) window.location.href=\"{0}\";</script>", Globals.ApplicationPath + "/admin/Default.aspx");
            ClientScriptManager clientScript = this.Page.ClientScript;
            if (!clientScript.IsClientScriptBlockRegistered(key))
            {
                clientScript.RegisterClientScriptBlock(base.GetType(), key, script);
            }
        }

        protected void ReloadPage(NameValueCollection queryStrings)
        {
            base.Response.Redirect(this.GenericReloadUrl(queryStrings));
        }

        protected void ReloadPage(NameValueCollection queryStrings, bool endResponse)
        {
            base.Response.Redirect(this.GenericReloadUrl(queryStrings), endResponse);
        }

        protected virtual void ShowMsg(ValidationResults validateResults)
        {
            StringBuilder builder = new StringBuilder();
            foreach (ValidationResult result in (IEnumerable<ValidationResult>) validateResults)
            {
                builder.Append(Formatter.FormatErrorMessage(result.Message));
            }
            this.ShowMsg(builder.ToString(), false);
        }

        protected virtual void ShowMsg(string msg, bool success)
        {
            string str = string.Format("ShowMsg(\"{0}\", {1})", msg, success ? "true" : "false");
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered("ServerMessageScript"))
            {
                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "ServerMessageScript", "<script language='JavaScript' defer='defer'>setTimeout(function(){" + str + "},300);</script>");
            }
        }
    }
}

